#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int pipefd[2];
    pipe(pipefd);

    pid_t id = fork();
    if (id == 0)
    {
        // 子进程
        close(pipefd[1]);
        int fd = open("/dev/pts/5", O_WRONLY, 0666);
        dup2(fd, 1); 
        char buffer[1024];
        while (true)
        {
            int size = read(pipefd[0], buffer, sizeof(buffer));
            if (size == 0)
                break;
            std::cout<< "child get : " << buffer << std::endl;
            sleep(1);
        }
        std::cout << "child quit! " << std::endl;
        exit(0);
    }

    // 父进程
    close(pipefd[0]);

    int cnt = 10;
    std::string buffer;

    while (cnt--)
    {
        buffer = std::to_string(10 - cnt) + " I am father";
        write(pipefd[1], buffer.c_str(), sizeof(buffer));
        std::cout << "parent deliver : " << buffer << std::endl;
        sleep(1);
    }

        std::cout << "parent quit! " << std::endl;

    close(pipefd[1]);
    waitpid(id, nullptr, 0);

    return 0;
}